﻿using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Core.ApiClient.App_Code.Swagger_Attribute
{
    /// <summary>
    /// 操作过过滤器 添加通用参数等
    /// </summary>
    public class AssignOperationVendorExtensions:IOperationFilter
    {
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation == null || context == null)
                return;

            operation.Parameters = operation.Parameters ?? new List<IParameter>();

            context.ApiDescription.TryGetMethodInfo(out MethodInfo method);



            // 是否进行普通验证
            var isAuthor = method.ReflectedType.BaseType.IsDefined(typeof(ApiAuthorizeAttribute),true);

            // 是否进行管理员验证
            var isProjectAuthor = method.IsDefined(typeof(ApiProjectMemberAttribute),true);

            // 是否忽略
            var isIgnoreAuthor = !method.IsDefined(typeof(IgnoreAuthorizeAttribute), true);


            if (isAuthor && isIgnoreAuthor)
            {
                operation.Parameters.Insert(0, new NonBodyParameter()
                {
                    Name = "Itool-Token",
                    In = "header",
                    Description = "身份验证",
                    Required = true,
                    Type = "header string"
                });
            }

            if (isProjectAuthor && isIgnoreAuthor)
            {
                operation.Parameters.Add(new NonBodyParameter()
                {
                    Name = "Itool-Project",
                    In = "header",
                    Description = "管理员身份验证",
                    Required = true,
                    Type = "header string"
                });
            }


            if (method.IsDefined(typeof(SwaggerFileUploadAttribute), true))
            {
                operation.Parameters.Add(new NonBodyParameter
                {
                    Name = "file",
                    In = "formData",
                    Description = "上传图片",
                    Required = (method.GetCustomAttribute(typeof(SwaggerFileUploadAttribute)) as SwaggerFileUploadAttribute).Required,
                    Type = "file"
                });
            }
        }

    }
}
